<template>
  <view class="search-page">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-input-wrap">
        <image src="/static/index/union.png" mode="widthFix" class="search-icon"></image>
        <input type="text" v-model="query.keyword" class="search-input" placeholder="请输入药品名/69码/货道号"
          placeholder-class="placeholder" @confirm="handleSearch" confirm-type="search" focus />
        <view class="clear-icon" @click="toCode">
          <image src="/static/index/scode.png" mode="widthFix" class="search-icon"></image>
        </view>
      </view>
      <view class="cancel-btn" @click="handleSearch">搜索</view>
    </view>
    <view class="list-container" v-if="dataList.length>0" :class="isShowWl?'active-containerR':''">
      <medicine :listData="dataList" @replenish="handleReplenish" :isGet="true" />
    </view>

    <!-- 无搜索结果 -->
    <view class="empty-result" v-if="!dataList">
      <image src="/static/images/empty-search.png" mode="aspectFit" class="empty-icon"></image>
      <view class="empty-text">暂无数据</view>
    </view>
    <uv-load-more :status="status" line height="60" paddingBottom="130" v-if="dataList.length!=0" />
  </view>

  <!-- 取药弹框 -->
  <uv-popup ref="popupRef" @close="closePopup" mode="center" round="10" :maskClick="false">
    <view class="popup-content">
      <view class="popup-title">{{ currentItem?.medicineName || '-' }}</view>
      <view class="input-row">
        <input type="number" v-model="replenishNum" placeholder="请输入取出数量" class="input-box" @blur="onReplenishInput" />
        <view class="stock-info">库存数量 {{ currentItem?.inventory || 0 }}</view>
      </view>
      <view class="button-group">
        <view class="cancel-btn" @click="closePopup">取消</view>
        <view class="confirm-btn" @click="confirmReplenish">确认取药</view>
      </view>
    </view>
  </uv-popup>
</template>

<script setup>
  import { ref } from 'vue'
  import medicine from '@/components/medicine/index.vue'
  import { getTakeOutList, takeOutSure } from '@/api/storeManage.js'
  import { onLoad, onReachBottom } from '@dcloudio/uni-app'

  const searchKeyword = ref('')
  const dataList = ref([])
  const listIn = ref([])
  const isShowWl = ref(false)

  const query = ref({
    cabinetId: '',
    keyword: '',
    pageNum: 1,
    pageSize: 10,
  })

  const status = ref('loadmore')
  const total = ref(0)
  const machineInfo = ref({})
  const heartbeat = ref({})

  onLoad(() => {
    getList()
  })
  // 弹框控制
  const popupRef = ref(null)
  const replenishNum = ref(0)
  const currentItem = ref(null)

  // 处理搜索
  const handleSearch = () => {
    init()
    if (query.value.keyword == "") {
      uni.showToast({
        title: '请输入药品名/69码/货道号',
        icon: 'none'
      })
      return
    }
    getList()
  }
  const init = () => {
    query.value.pageNum = 1
    dataList.value = []
    listIn.value = []
  }
  const toCode = () => {
    uni.scanCode({
      scanType: ['barCode', 'qrCode'],
      success: (res) => {
        query.value.keyword = res.result
      },
      fail: (err) => {
        uni.showToast({
          title: '扫码失败，请重试',
          icon: 'none'
        })
      }
    })
  }
  const getList = () => {
    query.value.cabinetId = uni.getStorageSync('machineInfo').id
    getTakeOutList(query.value).then(res => {
      if (res.code == 200) {
        listIn.value = query.value.pageNum == 1 ? res.rows : listIn.value.concat(res.rows)
        console.log(dataList.value.length, '--------7---------', listIn.value.length)
        dataList.value = []
        listIn.value.map((item, index) => {
          if (!item.medicineVo.slotName) {
            item.medicineVo.slotName = item.name
          }
          item.medicineVo.threshold = item.threshold || 0
          item.medicineVo.inventory = item.inventory || 0
          item.medicineVo.slotId = item.id
          dataList.value.push(item.medicineVo)
        })
        console.log(dataList.value.length, '--------8---------', listIn.value.length)
        total.value = res.total || 0
        status.value = listIn.value.length >= total.value ? 'nomore' : 'loadmore'

      }
    })
  }
  // 处理取药按钮点击
  const handleReplenish = (item) => {
    currentItem.value = item
    popupRef.value.open()
    isShowWl.value = true
  }

  // 关闭弹框
  const closePopup = () => {
    popupRef.value.close()
    isShowWl.value = false
    replenishNum.value = 0
  }

  // 取药数量输入校验，只能输入正整数
  const validateReplenishNum = (value) => {
    // 确保是正整数且大于0
    if (value == '' || parseInt(value) <= 0) {
      return ''
    }
    // 如果输入的是浮点数，只取整数部分
    return parseInt(value).toString()
  }

  // 新增onReplenishInput方法
  const onReplenishInput = (e) => {
    replenishNum.value = validateReplenishNum(e.detail.value)
  }

  // 确认取药
  const confirmReplenish = () => {
    // 执行输入校验
    onReplenishInput({ detail: { value: replenishNum.value } })
    if (!replenishNum.value || !/^[1-9]\d*$/.test(replenishNum.value)) {
      uni.showToast({
        title: '请输入正确的正整数数量',
        icon: 'none'
      })
      return
    }
    console.log('取药商品:', currentItem.value)
    // TODO: 调用取药接口
    takeOutSure({
      cabinetId: uni.getStorageSync('machineInfo').id,
      slotId: currentItem.value.slotId,
      quantity: replenishNum.value
    }).then(res => {
      if (res.code == 200) {
        uni.showToast({
          title: '取药成功',
          icon: 'success'
        })
        init()
        getList()
        closePopup()
      }
    })
  }

  // 上拉加载
  onReachBottom(() => {
    if (status.value == 'loadmore') {
      query.value.pageNum++
      getList()
    }
  });

</script>

<style lang="scss">
  .search-page {
    min-height: 100vh;
    background: #f5f5f5;
    overflow: scroll;

    .search-header {
      display: flex;
      align-items: center;
      padding: 16rpx 30rpx;
      background: #fff;
      border-bottom: 1rpx solid #f5f5f5;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 100;

      .search-input-wrap {
        flex: 1;
        height: 64rpx;
        background: #f7f7f7;
        border-radius: 32rpx;
        display: flex;
        align-items: center;
        padding: 0 24rpx;
        margin-right: 20rpx;

        .search-icon {
          width: 32rpx;
          height: 32rpx;
          margin-right: 12rpx;
        }

        .search-input {
          flex: 1;
          height: 100%;
          font-size: 26rpx;
        }

        .placeholder {
          color: #999;
          font-size: 26rpx;
        }

        .clear-icon {
          width: 36rpx;
          height: 36rpx;
          color: #999;
        }
      }

      .cancel-btn {
        font-size: 26rpx;
        color: #3B82F6;
        padding: 0 4rpx;
      }
    }

    .list-container {
      flex: 1;
      background: #f5f5f5;
      padding: 20rpx;
      margin-top: 12%;
    }

    .empty-result {
      padding-top: 200rpx;
      text-align: center;

      .empty-icon {
        width: 180rpx;
        height: 180rpx;
        margin-bottom: 16rpx;
      }

      .empty-text {
        font-size: 26rpx;
        color: #999;
      }
    }
  }

  .popup-content {
    width: 580rpx;
    background: #fff;
    border-radius: 20rpx;
    padding: 40rpx;

    .popup-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      text-align: left;
      margin-bottom: 30rpx;
    }

    .input-row {
      margin-bottom: 40rpx;

      .input-box {
        width: 94%;
        height: 88rpx;
        background: #F5F5F5;
        border-radius: 12rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        margin-bottom: 20rpx;
      }

      .stock-info {
        text-align: center;
        font-size: 28rpx;
        margin-top: 40rpx;
        border-bottom: 1rpx solid #f5f5f5;
        padding-bottom: 26rpx;
        color: #3D3D3D;
      }
    }

    .button-group {
      display: flex;
      justify-content: space-between;
      gap: 20rpx;

      .cancel-btn,
      .confirm-btn {
        flex: 1;
        height: 78rpx;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
      }

      .cancel-btn {
        background: #F2F4F7;
        color: #9CA3AF;
      }

      .confirm-btn {
        background: #3B82F6;
        color: #fff;
      }
    }
  }

  .active-containerR {
    position: fixed;
    width: 94.8%;
  }
</style>